<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="text" id="content">
    <input type="submit" id="up">
    <hr>
    <div id="chat">
        <div id="notic">当前在线用户: <span id="totalPeople">0</span></div>
    </div>
</body>
</html>
<script>
    let websocketUrl = 'ws://'+ location.host +'/intoRoom';
    let websocket = new WebSocket(websocketUrl);


    websocket.onopen = function() {
        console.log("房间链接成功!");
    }
    websocket.onclose = function() {
        console.log("房间断开链接");
    }
    websocket.onerror = function() {
        console.log("房间出现异常");
    }
    window.onbeforeunload = function() {
        websocket.close();
    }
    websocket.onmessage = function(e) {
        console.log(e.data);
        let resp = JSON.parse(e.data);
        let chat = document.querySelector('#chat');
        let div = document.createElement('div');
        if(resp.message == 'people'){
            let total = document.querySelector("#totalPeople");
            total.innerHTML = resp.number;
        }
        if(resp.message == 'chatMessage'){
            div.innerHTML=resp.content;
        }
        chat.appendChild(div);
    }

    let submit = document.querySelector("#up");
    submit.onclick = function() {
        let content = document.querySelector("#content");
        let req = {
            content: content.value,
        }
        websocket.send(JSON.stringify(req));
    }
</script>